package com.example.mystore.controller;

import com.example.mystore.model.Product;
import com.example.mystore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpStatus;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;
    //添加商品
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> addProduct(@RequestPart("product") Product product, @RequestPart("images") List<MultipartFile> images) {
        try {
            processProductImages(product, images);
            product.setIsHot(2);
            product.setStatus(1);
            productService.addProduct(product);
            return ResponseEntity.ok("Product added successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error saving product");
        }
    }
   //商品的修改
    @PatchMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> updateProduct(@PathVariable int id, @RequestPart("product") Product product, @RequestPart(value = "images", required = false) List<MultipartFile> images) {
        try {
            // 获取现有的产品信息
            Product existingProduct = productService.getProductById(id);
            if (existingProduct == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Product not found");
            }

            // 如果 images 为空，则使用现有的图片 URL
            if (images == null || images.isEmpty()) {
                product.setIconUrl(existingProduct.getIconUrl());
                product.setSubImages(existingProduct.getSubImages());
            } else {
                processProductImages(product, images);
            }

            product.setId(id);
            productService.updateProduct(product);
            return ResponseEntity.ok("Product updated successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error updating product");
        }
    }

    private void processProductImages(Product product, List<MultipartFile> images) throws Exception {
        if (images != null && !images.isEmpty()) {
            // 处理主要图像
            String mainImageUrl = productService.saveImage(images.get(0));
            product.setIconUrl(mainImageUrl);
            // 处理次要图像
            List<String> subImageUrls = new ArrayList<>();
            for (int i = 1; i < images.size(); i++) {
                String subImageUrl = productService.saveImage(images.get(i));
                subImageUrls.add(subImageUrl);
            }
            product.setSubImages(String.join(",", subImageUrls));
        }
    }
    @PutMapping("/{id}/toggle-status")
    public ResponseEntity<String> toggleProductStatus(@PathVariable int id) {
        try {
            productService.toggleProductStatus(id);
            return ResponseEntity.ok("Product status toggled successfully");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Product not found");
        }
    }

    @PutMapping("/{id}/toggle-hot")
    public ResponseEntity<String> toggleHotStatus(@PathVariable int id) {
        try {
            productService.toggleHotStatus(id);
            return ResponseEntity.ok("Product hot status toggled successfully");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Product not found");
        }
    }

    @GetMapping("/{id}")
    public Product getProductById(@PathVariable int id) {
        return productService.getProductById(id);
    }

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }



}
